package com.hanxiaozhang.io.sockethttp;

import com.hanxiaozhang.utils.StringUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.util.HashMap;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author hanxinghua
 * @create 2023/6/25
 * @since 1.0.0
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class ResponseEntity {

    public ResponseEntity(Integer stateCode, String reason, Map<String, String> headers, String body) {
        this.stateCode = stateCode;
        this.reason = reason;
        this.headers = headers;
        this.body = body;
    }

    /**
     * 状态
     */
    private String stateLine;

    /**
     * 版本协议
     */
    private String requestAndVersion;

    /**
     * 状态码
     */
    private Integer stateCode;

    /**
     * 原因
     */
    private String reason;

    /**
     * 响应header
     */
    private Map<String, String> headers;

    /**
     * 响应内容
     */
    private String body;


    public byte[] responseToBytes(RequestEntity request) {

        // 处理状态行
        StringBuilder sb = new StringBuilder();
        this.requestAndVersion = request.getRequestAndVersion();
        this.stateLine = request.getRequestAndVersion() + " " + stateCode + " " + reason;
        sb.append(stateLine);
        sb.append("\r\n");
        // 处理响应header
        Map<String, String> tempHeaders = new HashMap<>(16);
        tempHeaders.putAll(request.getHeaders());
        if (this.headers != null && !this.headers.isEmpty()) {
            tempHeaders.putAll(this.headers);
        }
        if (StringUtil.isNotBlank(this.body)) {
            tempHeaders.put("Content-Length", String.valueOf(this.body.length()));
        }
        tempHeaders.forEach((k, v) -> {
            sb.append(k + ": " + v + "\r\n");
        });
        sb.append("\r\n");
        // 处理响应body
        if (StringUtil.isNotBlank(this.body)) {
            sb.append(this.body);
        }
        return sb.toString().getBytes();
    }

}
